import { Controller } from "egg";
import { IndexCondition } from "../common";

export default class WarehouseController extends Controller {
  /**
   * 查询
   */
  public async index() {
    const { ctx } = this;
    const { pageSize, pageIndex, business } = ctx.query;
    const _listCondition: IndexCondition = {
      select:
        "flow drug productionDate expirationDate business amount batches createdAt",
      find: {
        ...(business && { business }),
      },
      ...(pageIndex && { pageIndex: parseInt(pageIndex) - 1 }),
      ...(pageSize && { pageSize: parseInt(pageSize) }),
    };
    const res = await ctx.service.warehouse.findList(_listCondition);
    ctx.helper.success({ ctx, res, msg: "查询成功" });
  }

  /**
   * 入库
   */
  public async create() {
    const { ctx } = this;
    const {
      drug_name,
      brand_name,
      standard,
      supply_name,
      price,
      entryPrice,
      business_name,
    } = ctx.request.body;
    try {
      // 查询当前商业公司是否存在
      const _business = await ctx.service.businessCompany.findByName(
        business_name
      );
      if (!_business) {
        await ctx.service.businessCompany.add({
          name: business_name,
        });
      }
      // 第五步：查看当前药品是否存在，不存在就添加到药品库中
      let _drug = await ctx.service.drug.findByName({
        name: drug_name,
        brand: brand_name,
        standard,
        factory: supply_name,
      });
      if (!_drug) {
        _drug = await ctx.service.drug.add({
          name: drug_name,
          brand: brand_name,
          standard,
          factory: supply_name,
          price,
          entryPrice,
        });
      }
      // 入库
      const res = await ctx.service.warehouse.add(ctx.request.body, _drug);
      if (!res) {
        return ctx.helper.error({ ctx, errorType: "commonOperateFail" });
      }
      ctx.helper.success({ ctx, res, msg: "入库成功！" });
    } catch (e) {
      return ctx.helper.error({ ctx, errorType: "commonOperateFail" });
    }
  }

  /**
   * 调拨
   */
  public async update() {
    const { ctx, service } = this;
    const { id } = ctx.params;
    const { business_name, amount } = ctx.request.body;
    try {
      // 查询当前调度到的商业公司是否存在
      let _business = await ctx.service.businessCompany.findByName(
        business_name
      );
      if (!_business) {
        //  如果不存在，就添加商业公司
        _business = await ctx.service.businessCompany.add({
          name: business_name,
        });
      }
      // 查询当前库存是否存在
      const _warehouse = await ctx.service.warehouse.findByOne({ _id: id });
      if (!_warehouse) {
        return ctx.helper.error({ ctx, errorType: "warehouseNoExitsError" });
      }
      // 拿到当前库存信息,如果库存为0就不允许进行操作
      if (_warehouse.amount === 0 || _warehouse.amount < amount) {
        return ctx.helper.error({ ctx, errorType: "warehouseAmountError" });
      }
      // 同一个商业公司不接受调度
      if (business_name === _warehouse.business) {
        return ctx.helper.error({ ctx, errorType: "businessError" });
      }
      const res = await service.warehouse.transfer(
        {
          id,
          business_name,
          amount,
        },
        _warehouse
      );
      if (!res) {
        return ctx.helper.error({ ctx, errorType: "commonOperateFail" });
      }
      ctx.helper.success({ ctx, res, msg: "调拨成功！" });
    } catch (e) {
      return ctx.helper.error({ ctx, errorType: "commonOperateFail" });
    }
  }

  /**
   * 出库
   */
  public async outWare() {
    const { ctx } = this;
    const { id, hospital_name, amount } = ctx.request.body;
    try {
      // 判断当前的医院是否存在，不存在就添加
      const _hospital = await ctx.service.hospital.findByName(hospital_name);
      if (!_hospital) {
        return ctx.helper.error({ ctx, errorType: "warehouseNoHospitalError" });
      }
      // 判断当前库存是否存在
      const _warehouse = await ctx.service.warehouse.findByOne({ _id: id });
      if (!_warehouse) {
        return ctx.helper.error({ ctx, errorType: "warehouseNoExitsError" });
      }
      // 拿到当前库存信息,如果库存为0就不允许进行操作
      if (_warehouse.amount === 0 || _warehouse.amount < amount) {
        return ctx.helper.error({ ctx, errorType: "warehouseAmountError" });
      }
      // 出库操作
      const res = await ctx.service.warehouse.outWare({
        id,
        hospital_name,
        amount,
      });
      if (!res) {
        return ctx.helper.error({ ctx, errorType: "commonOperateFail" });
      }
      return ctx.helper.success({ ctx, res, msg: "出库成功！" });
    } catch (e) {
      return ctx.helper.error({ ctx, errorType: "commonOperateFail" });
    }
  }

  /**
   * 退货
   */
  public async recede() {
    const { ctx } = this;
    const { id } = ctx.params;
    // 查询当前出库记录是否存在
    const _record = await ctx.model.WarehouseRecord.findOne({
      _id: id,
      type: "出库",
    });
    if (!_record) {
      return ctx.helper.error({ ctx, errorType: "warehouseRecordError" });
    }
    if (_record.type !== "出库") {
      return ctx.helper.error({ ctx, errorType: "warehouseRecordTypeError" });
    }
    const res = await ctx.service.warehouse.recede(_record);
    if (!res) {
      return ctx.helper.error({ ctx, errorType: "commonOperateFail" });
    }
    ctx.helper.success({ ctx, res, msg: "回退成功！" });
  }

  /**
   * 获取库存操作记录
   */
  public async getRecordList() {
    const { ctx } = this;
    const { pageIndex, pageSize, type, receive_name, level, createdAt } =
      ctx.query;
    const _listCondition: IndexCondition = {
      select:
        "_id warehouse supply_name receive_name amount level type operate_msg createdAt id",
      populate: [
        {
          path: "warehouse",
          select:
            "flow business drug amount batches productionDate expirationDate createdAt",
        },
      ],
      find: {
        ...(type && { type }),
        ...(receive_name && { receive_name }),
        ...(level && { level }),
        ...(createdAt && { createdAt }),
      },
      ...(pageIndex && { pageIndex: parseInt(pageIndex) - 1 }),
      ...(pageSize && { pageSize: parseInt(pageSize) }),
    };
    const res = await ctx.service.warehouse.getRecordList(_listCondition);
    if (!res) {
      return ctx.helper.error({ ctx, errorType: "commonOperateFail" });
    }
    ctx.helper.success({ ctx, res });
  }
}
